﻿using System;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using Tools.Properties;

namespace Tools.FileUtills
{
    public class FileUtils
    {
        // private static String filePath = "D:/publicCode/Tools/Tools/Tools/files.json";
        private static String filePath = "files.json";

        /// <summary>
        /// 读取 配置文件 
        /// </summary>
        /// <returns></returns>
        public static String[] readFile()
        {
            var content = File.ReadAllText(filePath);
            return content.Replace("\n", "").Replace("\r", "").Split(',');
        }

        public static void addItemInfo(String path)
        {
            var dbFiles = readFile();
            if (dbFiles.Contains(path))
            {
                MessageBox.Show("路径为: " + path + " 的文件已经存在 ");
                return;
            }

            var streamWriter = File.AppendText(filePath);
            streamWriter.WriteLine(path + ",");
            streamWriter.Close();
            MessageBox.Show("添加成功");
        }

        public static bool updateItemInfo(String oldPath, String oldFileName, String newName)
        {
            var file = readFile();
            if (file == null)
            {
                return false;
            }

            var finalPath = oldPath + "@" + oldFileName;

            if (file.Contains(finalPath))
            {
                var index = file.ToList().IndexOf(finalPath);
                var newPath = oldPath + "@" + newName;
                file.SetValue(newPath, index);
                Console.WriteLine("news file path : " , newPath);
                File.WriteAllText(filePath ,String.Join(",",file),Encoding.UTF8);
                return true;
            }
            else
            {
                return false;
            }
        }

        
        /// <summary>
        ///  搜索工具
        /// </summary>
        /// <param name="fileName">工具文件名称</param>
        public static ArrayList findFileByFileName(string fileName)
        {

            // 获取当前的文件列表  路径+@+文件名称
            var currentFiles = readFile();
            var result = new ArrayList();
            foreach (var currentFile in currentFiles)
            {
                if (currentFile.Split('@').Length == 2)
                {
                    var currentFileName = currentFile.Split('@')[1];
                    if (currentFileName.ToLower().Contains(fileName) || currentFileName.ToUpper().Contains(fileName) || currentFileName.Contains(fileName))
                    {
                        result.Add(currentFile);
                    }
                }
            
            }

            return result;
        }
    }
}